import React, { useCallback, useState } from 'react';
import { View, ScrollView, RefreshControl, StyleSheet, Dimensions, ActivityIndicator, TouchableOpacity } from 'react-native';
import { useTheme } from '../../components/theme/ThemeContext';
import { ThemedText } from '../../components/ThemedText';
import { ThemedView } from '../../components/ThemedView';
import { Header } from '../../components/Header';
import { ArtworkCard } from '../../components/ArtworkCard';
import { artworkService } from '../../utils/api/services';
import { ArtworkResponse, PaginatedData } from '../../utils/api/types';
import { MaterialIcons } from '@expo/vector-icons';
import { getFullURL, addTimestamp } from '../../utils/url';
import { useRouter } from 'expo-router';

const { width } = Dimensions.get('window');

export default function HomeScreen() {
  const { theme } = useTheme();
  const router = useRouter();
  const [refreshing, setRefreshing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [featuredArtworks, setFeaturedArtworks] = useState<ArtworkResponse[]>([]);
  const [recentArtworks, setRecentArtworks] = useState<ArtworkResponse[]>([]);

  // 刷新数据
  const onRefresh = useCallback(async () => {
    try {
      setRefreshing(true);
      setError(null);
      
      // 获取推荐作品
      const featuredResponse = await artworkService.listArtworks({
        limit: 5,
        offset: 0,
      });
      
      if (featuredResponse?.code === 200) {
        const paginatedData = featuredResponse.data as unknown as PaginatedData<ArtworkResponse>;
        if (paginatedData?.items) {
          const artworks = paginatedData.items.map(artwork => ({
            ...artwork,
            file_url: artwork.file_url ? (
              artwork.file_url.startsWith('http') ? artwork.file_url : getFullURL(artwork.file_url)
            ) : '',
            creator_id: artwork.creator_id || 0,
            description: artwork.description || '',
            tags: artwork.tags || []
          }));
          console.log('设置推荐作品:', artworks.length);
          setFeaturedArtworks(artworks);
        } else {
          console.warn('推荐作品数据格式异常:', featuredResponse);
          setFeaturedArtworks([]);
        }
      }

      // 获取最新作品
      const recentResponse = await artworkService.listArtworks({
        limit: 10,
        offset: 0,
      });
      
      if (recentResponse?.code === 200) {
        const paginatedData = recentResponse.data as unknown as PaginatedData<ArtworkResponse>;
        if (paginatedData?.items) {
          const artworks = paginatedData.items.map(artwork => ({
            ...artwork,
            file_url: artwork.file_url ? (
              artwork.file_url.startsWith('http') ? artwork.file_url : getFullURL(artwork.file_url)
            ) : '',
            creator_id: artwork.creator_id || 0,
            description: artwork.description || '',
            tags: artwork.tags || []
          }));
          console.log('设置最新作品:', artworks.length);
          setRecentArtworks(artworks);
        } else {
          console.warn('最新作品数据格式异常:', recentResponse);
          setRecentArtworks([]);
        }
      }
    } catch (err: any) {
      console.error('加载作品失败:', err);
      if (err.response) {
        console.error('错误响应:', JSON.stringify(err.response, null, 2));
      }
      setError(err.message || '加载作品失败，请下拉刷新重试');
      setFeaturedArtworks([]);
      setRecentArtworks([]);
    } finally {
      setRefreshing(false);
      setLoading(false);
    }
  }, []);

  // 首次加载时获取数据
  React.useEffect(() => {
    onRefresh();
  }, [onRefresh]);

  // 处理搜索点击
  const handleSearchPress = () => {
    router.push('/search');
  };

  // 加载状态
  if (loading && !refreshing) {
    return (
      <ThemedView style={styles.container}>
        <Header 
          title="AI作品档案馆" 
          rightComponent={
            <TouchableOpacity onPress={handleSearchPress}>
              <MaterialIcons 
                name="search" 
                size={24} 
                color={theme.colors.primary}
                style={styles.searchIcon}
              />
            </TouchableOpacity>
          }
        />
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.colors.primary} />
          <ThemedText style={styles.loadingText}>加载中...</ThemedText>
        </View>
      </ThemedView>
    );
  }

  const renderFeaturedArtworks = () => {
    if (!Array.isArray(featuredArtworks)) return null;
    
    return featuredArtworks.length > 0 ? (
      featuredArtworks.map((artwork) => (
        <ArtworkCard
          key={artwork.id}
          artwork={artwork}
          variant="featured"
        />
      ))
    ) : (
      <ThemedView variant="card" style={styles.emptyCard}>
        <ThemedText variant="body">暂无推荐作品</ThemedText>
      </ThemedView>
    );
  };

  const renderRecentArtworks = () => {
    if (!Array.isArray(recentArtworks)) return null;
    
    return recentArtworks.length > 0 ? (
      recentArtworks.map((artwork) => (
        <ArtworkCard
          key={artwork.id}
          artwork={artwork}
          variant="recent"
        />
      ))
    ) : (
      <ThemedView variant="card" style={styles.emptyCard}>
        <ThemedText variant="body">暂无最新作品</ThemedText>
      </ThemedView>
    );
  };

  return (
    <ThemedView style={styles.container}>
      <Header 
        title="AI作品档案馆" 
        rightComponent={
          <TouchableOpacity onPress={handleSearchPress}>
            <MaterialIcons 
              name="search" 
              size={24} 
              color={theme.colors.primary}
              style={styles.searchIcon}
            />
          </TouchableOpacity>
        }
      />
      
      <ScrollView
        style={styles.scrollView}
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
      >
        {error ? (
          <View style={styles.errorContainer}>
            <ThemedText style={styles.errorText}>{error}</ThemedText>
          </View>
        ) : (
          <>
            {/* 推荐作品区域 */}
            <View style={styles.section}>
              <ThemedText variant="h2" style={styles.sectionTitle}>
                推荐作品
              </ThemedText>
              <ScrollView horizontal showsHorizontalScrollIndicator={false}>
                {renderFeaturedArtworks()}
              </ScrollView>
            </View>

            {/* 最新作品区域 */}
            <View style={styles.section}>
              <ThemedText variant="h2" style={styles.sectionTitle}>
                最新作品
              </ThemedText>
              <View style={styles.recentGrid}>
                {renderRecentArtworks()}
              </View>
            </View>
          </>
        )}
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    flex: 1,
  },
  searchIcon: {
    padding: 8,
  },
  section: {
    padding: 16,
  },
  sectionTitle: {
    marginBottom: 12,
  },
  featuredCard: {
    width: width * 0.8,
    height: 200,
    marginRight: 16,
    padding: 16,
    borderRadius: 12,
  },
  recentGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  recentCard: {
    width: (width - 48) / 2,
    height: 160,
    marginBottom: 16,
    padding: 12,
    borderRadius: 8,
  },
  artworkTitle: {
    marginBottom: 8,
  },
  artworkDescription: {
    opacity: 0.7,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 12,
  },
  errorContainer: {
    flex: 1,
    padding: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    textAlign: 'center',
    color: 'red',
  },
  emptyCard: {
    width: width * 0.8,
    height: 200,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16,
    borderRadius: 12,
  },
});
